// import QtQuick 1.0 // to target S60 5th Edition or Maemo 5
import QtQuick 1.1
import "./js/js.js" as Js

Item {
    id: search_page
    width: 450
    height: 700

    property int text_pixel_size: 22
    property string search_option_detail: ""
    property int search_option_index: 1

    /////////////////////////////////////////////////      function that connect the sogou server
    function sogou_search()
    {
        function search() {}
        search.prototype = {
            update: function(result)
                    {
                        if(result.error_msg == null)
                        {
                            if(result.status == "error") {
                                console.log("result error : " + result.response.error.msg);
//                                loadingCover.hideLoadingCover();
                                root.set_notification_loader(4500, "搜索错误：" + result.response.error.msg);
//                                warningDialog.warningText = "Incorrect nick name or password, please try again.";
//                                warningDialog.ifProgramClosing = false;
//                                warningDialog.showPage();
                            }
                            else /*if(result.status == "ok") */{
                                console.log("result count : " + result.response.data.feature.length);
                                root.set_notification_loader(1500, "搜索成功！");
                                search_model.clear();
                                var length = result.response.data.feature.length;

                                for (var i = 0; i < length; i ++)
                                {
                                    search_model.append({
                                                            "phone": result.response.data.feature[i].detail.phone,
                                                            "category": result.response.data.feature[i].detail.category,
                                                            "address": result.response.data.feature[i].detail.address,
                                                            "city": result.response.data.feature[i].detail.city,
                                                            "caption": result.response.data.feature[i].caption,
                                                            "level": result.response.data.feature[i].level,
                                                            "points": result.response.data.feature[i].points.txt
                                                        });
                                }

//                                APIsRequest.login(glValue.loginUserName, glValue.loginPassword,
//                                                  glValue.appTicket, glValue.appKey, new requestLogin());
                            }
                        }
                        else {
//                            loadingCover.hideLoadingCover();
                            root.set_notification_loader(3000, "当前网络连接出现问题，请重试");
//                            Js.handleProgramError("The application is going to close because network error, please check your network connection and try again.",true)

                        }
                    }
        }

//        APIsRequest.getDomainUrl(glValue.loginUserName, new requestDomainUrl());
        var lonlat =  positionSource.position.coordinate.longitude + "," + positionSource.position.coordinate.latitude ;
        console.log("keyword:" + search_input.text + "range=" + search_option_detail + " lonlat= " + lonlat);
        switch (search_option_index)
        {
        case 0:
            Js.sogouSearchAPI(new search(), "keyword:" + search_input.text, "center:" + lonlat + ":1000:0");
            break;
        case 1:
            Js.sogouSearchAPI(new search(), "keyword:" + search_input.text, "bound:" + js.mapbounds + ":0");
            break;
        case 2:
            Js.sogouSearchAPI(new search(), "keyword:" + search_input.text, "city:全国");
            break;
        }
//        Js.sogouSearchAPI(new search(), "keyword:" + search_input.text, search_option_detail);
        root.set_notification_loader(3000, "等待服务器响应中，响应时间取决于当前网络状况");
    }

    /////////////////////////////////////////////////      cover the background to avoid other MouseArea active
    MouseArea
    {
        anchors.fill: parent

        onClicked:
        {
            search_input.focus = false;
        }
    }

    /////////////////////////////////////////////////      title
    Text {
        id: title
//        y: 16
        height: 80
        anchors.top: parent.top
        text: "位置搜索"
        color: "white"
        anchors.topMargin: 10
        anchors.left: parent.left
        anchors.leftMargin: 10
        font.pixelSize: 55
    }

    /////////////////////////////////////////////////      search_rectangle
    Rectangle {
        id: search_rectangle
        width: 200
        height: 68
        color: "white"
        clip: true
        anchors.top: title.bottom
        anchors.topMargin: 10
        anchors.left: parent.left
        anchors.leftMargin: 10

        TextInput
        {
            id: search_input
            width: 200
            height: 50
            y: 15
            text: ""
            anchors.horizontalCenter: parent.horizontalCenter
//            anchors.bottom: parent.bottom
//            anchors.verticalCenter: parent.verticalCenter
            horizontalAlignment: TextInput.AlignHCenter
            font.pixelSize: 33
        }
    }

    Mbutton {
        id: search_mbutton
        y: 94
        anchors.left: search_rectangle.right
        anchors.leftMargin: 10
        anchors.verticalCenter: search_rectangle.verticalCenter
        textstring: "搜索"
        pro_width: 160

        onButtonclick:
        {
            search_input.focus = false;
            sogou_search();
            search_options_panel.state = "hide";
            search_options_panel.isShow = false;
        }
    }

    /////////////////////////////////////////////////      search_options
    Item {
        id: search_options_panel
        width: search_rectangle.width
        height: 300
        anchors.top: search_rectangle.bottom
        anchors.topMargin: 10
        anchors.left: parent.left
        anchors.leftMargin: 10
        clip: true
        state: "hide"

        property bool isShow: false

        states: [
            State {
                name: "hide"
                PropertyChanges {
                    target: search_options_panel
                    height: search_option_show.height
                }

                PropertyChanges {
                    target: search_options_column
                    opacity: 0
                }
            }
        ]

        Behavior on height {
            PropertyAnimation { duration: 100; easing.type: Easing.OutQuad }
        }

        Behavior on opacity {
            PropertyAnimation { duration: 100; easing.type: Easing.OutQuad }
        }

        Mbutton {
            id: search_option_show
            pro_width: parent.width
            pro_height: 70
            textstring: "搜索选项"
            anchors.left: parent.left
            anchors.leftMargin: 0
            anchors.top: parent.top
            anchors.topMargin: 0

            onButtonclick:
            {
                if (!search_options_panel.isShow)
                {
                    search_options_panel.state = "";
                    search_options_panel.isShow = true;
                }
                else
                {
                    search_options_panel.state = "hide";
                    search_options_panel.isShow = false;
                }
            }
        }

        Column {
            id: search_options_column
            x: 0
            y: 0
            width: parent.width
            height: 195
            anchors.rightMargin: 0
            anchors.leftMargin: 0
            anchors.topMargin: 80
            spacing: 20
            anchors.bottomMargin: 0
            anchors.fill: parent

            Behavior on opacity {
                PropertyAnimation { duration: 200; easing.type: Easing.OutQuad }
            }

            CheckBox {
                id: checkbox_around_me
                x: 0
                y: 54
                textstring: "自己周围"
                isCheck: false

                onCheck_statue:
                {
//                    var lonlat =  positionSource.position.coordinate.longitude + "," + positionSource.position.coordinate.latitude ;
                    checkbox_around_me.isCheck = true;
                    checkbox_current_map.isCheck = false;
                    checkbox_whole_country.isCheck = false;
//                    search_option_detail = "center:" + lonlat + ":1000:0";
//                    console.log("around me : " + search_option_detail);
                    search_option_index = 0;
                }
            }

            CheckBox {
                id: checkbox_current_map
                x: 0
                y: 150
                textstring: "当前地图"
                isCheck: true

                onCheck_statue:
                {
//                    web_view_map.evaluateJavaScript("getboundforqml()");
                    checkbox_around_me.isCheck = false;
                    checkbox_current_map.isCheck = true;
                    checkbox_whole_country.isCheck = false;
//                    search_option_detail = "bound:" + js.mapbounds + ":0"
//                    console.log("current_map : " + search_option_detail);
                    search_option_index = 1;
                }
            }

            CheckBox {
                id: checkbox_whole_country
                x: 0
                y: 100
                textstring: "全国范围"
                isCheck: false

                onCheck_statue:
                {
//                    search_option_detail = "city:全国";
                    checkbox_around_me.isCheck = false;
                    checkbox_current_map.isCheck = false;
                    checkbox_whole_country.isCheck = true;
                    search_option_index = 2;
                }
            }

//            function options_changed()
//            {

//            }
        }

    }

    /////////////////////////////////////////////////      ListView search
    ListView {
        id: list_view_search
        width: 380
        anchors.bottom: parent.bottom
        anchors.bottomMargin: 10
        anchors.top: search_options_panel.bottom
        anchors.topMargin: 10
        anchors.left: parent.left
        anchors.leftMargin: 10
        delegate: recipeDelegate
        model: search_model
        clip: true
        boundsBehavior: Flickable.StopAtBounds

        Behavior on height {
            PropertyAnimation { duration: 100; easing.type: Easing.OutQuad }
        }
    }

    // Delegate for the recipes.  This delegate has two modes:
    // 1. List mode (default), which just shows the picture and title of the recipe.
    // 2. Details mode, which also shows the ingredients and method.
    Component {
        id: recipeDelegate

        Item {
            id: recipe

            // Create a property to contain the visibility of the details.
            // We can bind multiple element's opacity to this one property,
            // rather than having a "PropertyChanges" line for each element we
            // want to fade.
            property real detailsOpacity : 0

            width: list_view_search.width
            height: topLayout.height + 20

            // A simple rounded rectangle for the background
            Rectangle {
                id: background
                x: 2; y: 2; width: parent.width - x*2; height: parent.height - y*2
                color: "ivory"
                border.color: "orange"
                radius: 5
                opacity: 0
            }

            // This mouse region covers the entire delegate.
            // When clicked it changes mode to 'Details'.  If we are already
            // in Details mode, then no change will happen.
            MouseArea {
                anchors.fill: parent
                onClicked:
                {
                    recipe.state = 'Details';
                    search_page.state = "result";
                }
            }

            // Lay out the page: picture, title and ingredients at the top, and method at the
            // bottom.  Note that elements that should not be visible in the list
            // mode have their opacity set to recipe.detailsOpacity.
//            Row {
//                id: topLayout
//                x: 10; y: 10; height: 60; width: parent.width
//                spacing: 10

//                Image {
//                    id: recipeImage
//                    width: 0/*50*/; height: 50
//                    source: ""
//                }

                Column {
                    id: topLayout
                    width: parent.width //height: parent.height
                    height: cap.paintedHeight + add.paintedHeight + 5
                    spacing: 5

                    Text {
                        id: cap
                        text: caption
                        wrapMode: Text.WrapAnywhere
                        width: parent.width
                        font.bold: true; font.pixelSize: text_pixel_size
                        color: "white"
                    }

                    //                            Text {
                    //                                text: "Ingredients"
                    //                                font.pointSize: 12; font.bold: true
                    //                                opacity: recipe.detailsOpacity
                    //                            }

                    Text {
                        id: add
                        text: address
                        wrapMode: Text.WordWrap
                        width: parent.width
                        font.pixelSize: text_pixel_size
                        color: "white"
//                        opacity: recipe.detailsOpacity
                    }

//                    Text {
//                        text: points
//                        wrapMode: Text.WordWrap
//                        width: parent.width
//                        font.pixelSize: text_pixel_size
//                        opacity: recipe.detailsOpacity
//                    }
                }
//            }
            // important!!
            Item {
                id: details
                x: 10; width: parent.width - 20
                anchors { top: topLayout.bottom; topMargin: 10; bottom: parent.bottom; bottomMargin: 10 }
                opacity: recipe.detailsOpacity

                // add buttons here
                Column
                {
                    anchors.fill: parent
                    anchors.topMargin: 20
                    spacing: 20

                    Mbutton {
                        id: text_phone
                        pro_width: 350
                        pro_height: 60
                        textstring: "电话：" + phone
                        text_size: text_pixel_size + 3
//                        color: "white"

                        onButtonclick:
                        {
                            Qt.openUrlExternally("tel:" + phone);
                        }
                    }

                    Text {
                        id: text_category
                        text: "类别：" + category
                        font.pixelSize: text_pixel_size + 5
                        color: "white"
                    }

                    Row
                    {
                        spacing: 50
                        Mbutton
                        {
                            id: useAs
                            pro_width: 150
                            pro_height: 50
                            textstring: "用途"
                            text_size: text_pixel_size

                            onButtonclick:
                            {
                                loader_use_as.source = "LocationUseAs.qml";
                                loader_use_as.item.set_location(address, points);
                            }
                        }

                        Mbutton {
                            y: useAs.y
                            pro_width: 150
                            pro_height: 50
//                            anchors { right: background.right; rightMargin: 10; }
                            opacity: recipe.detailsOpacity
                            textstring: "返回"
                            text_size: text_pixel_size

                            onButtonclick:
                            {
                                recipe.state = '';
                                search_page.state = "";
                            }
                        }
                    }

//                    Mbutton
//                    {
//                        width: 150
//                        height: 50
//                        textstring: "×÷ÖŐµă"

//                        onButtonclick:
//                        {
////                            web_view_map.end = title;
////                            mainApp.useInfobox("ÖŐµăŁş" + web_view_map.end);
//                        }
//                    }

//                    Mbutton
//                    {
//                        width: 150
//                        height: 50
//                        textstring: "ż´µŘÍĽ"

//                        onButtonclick:
//                        {
////                            web_view_map.setsearchresult_poi(poi);
////                            web_view_map.state === 'state1' ? web_view_map.state = "" : web_view_map.state = 'state1' ;
////                            inputpanel.state === 'state1' ? inputpanel.state = "" : inputpanel.state = 'state1' ;
//                        }
//                    }
                }
                //                        Text {
                //                            id: methodTitle
                //                            anchors.top: parent.top
                //                            text: "Method"
                //                            font.pointSize: 12; font.bold: true
                //                        }

                //                        Flickable {
                //                            id: flick
                //                            width: parent.width
                //                            anchors { top: methodTitle.bottom; bottom: parent.bottom }
                //                            contentHeight: methodText.height
                //                            clip: true

                //                            Text { id: methodText; text: method; wrapMode: Text.WordWrap; width: details.width }
                //                        }

                //                        Image {
                //                            anchors { right: flick.right; top: flick.top }
                //                            source: "content/pics/moreUp.png"
                //                            opacity: flick.atYBeginning ? 0 : 1
                //                        }

                //                        Image {
                //                            anchors { right: flick.right; bottom: flick.bottom }
                //                            source: "content/pics/moreDown.png"
                //                            opacity: flick.atYEnd ? 0 : 1
                //                        }
            }

            // A button to close the detailed view, i.e. set the state back to default ('').
//            Mbutton {
//                y: useAs.y
//                pro_width: 150
//                pro_height: 50
//                anchors { right: background.right; rightMargin: 10; }
//                opacity: recipe.detailsOpacity
//                textstring: "返回"
//                text_size: text_pixel_size

//                onButtonclick: recipe.state = '';
//            }

            states: State {
                name: "Details"

                PropertyChanges { target: background; color: "white" }
//                PropertyChanges { target: recipeImage; width: 130; height: 130 } // Make picture bigger
                PropertyChanges { target: recipe; detailsOpacity: 1; x: 0 } // Make details visible
                PropertyChanges { target: recipe; explicit: true; height: list_view_search.height + 68 } // Fill the entire list area with the detailed view

                // Move the list so that this item is at the top.
                PropertyChanges { target: recipe.ListView.view; explicit: true; contentY: recipe.y }

                // Disallow flicking while we're in detailed view
                PropertyChanges { target: recipe.ListView.view; interactive: false }
            }

            transitions: Transition {
                // Make the state changes smooth
                ParallelAnimation {
                    ColorAnimation { property: "color"; duration: 100 }
                    NumberAnimation { duration: 100; properties: "detailsOpacity,x,contentY,height,width" }
                }
            }
        }
    }

    /////////////////////////////////////////////////      model
    ListModel
    {
        id: search_model
    }

    /////////////////////////////////////////////////      load the LocationUseAs
    Loader
    {
        id: loader_use_as
        width: 480
        height: 854
//        anchors.fill: parent
        source: ""
    }

    Connections
    {
        id: connect_use_as
        target: loader_use_as.item

        onCancel_this:
        {
            loader_use_as.source = "";
        }

        onUse_as_start:
        {
            data_container.bus_start_text = l_text;
            data_container.bus_start_lonlat = "new sogou.maps.Point(" + l_lonlat + ")";
            loader_use_as.source = "";
        }

        onUse_as_end:
        {
            data_container.bus_end_text = l_text;
            data_container.bus_end_lonlat = "new sogou.maps.Point(" + l_lonlat + ")";
            loader_use_as.source = "";
        }

        onShow_on_map:
        {
            loader_use_as.source = "";
            web_view_map.set_marker(l_lonlat);
            web_view_map.panto(l_lonlat);
            set_notification_loader(6000, l_text);
            root.switch_map_panel();
        }
    }

    states: [
        State {
            name: "result"

            PropertyChanges {
                target: search_rectangle
                height: 0
                opacity: 0
            }

            PropertyChanges {
                target: search_mbutton
                height: 0
                opacity: 0
            }

            PropertyChanges {
                target: search_options_panel
                opacity: 0
            }
        }
    ]

    transitions: Transition {
        // Make the state changes smooth
        ParallelAnimation {
            NumberAnimation { duration: 100; properties: "opacity,height" }
        }
    }
}
